<?php
/**
 * 知食
 * User: Tsang
 * Date: 2017/12/4 11:27
 *
 */

namespace app\admin\Controller;


class KnowFoods extends Common
{


    /**
     * 知食列表
     */
    public function index(){
        $list = db('foods_knowledge')->where([
            'status' => array('neq',ARTICLE_STATUS_DELETE)
        ])
            ->order('sort desc')
            ->order('create_time desc')
            ->paginate(15);
        $this->assign('list',$list);
        return $this->fetch();
    }

    /**
     * 知食编辑
     */
    public function det(){
        $id = input('id/d');
        $m_fk = db('foods_knowledge');
        if($id > 0){
            $article = $m_fk->where(['id' => $id,'status' => array('neq',ARTICLE_STATUS_DELETE)])->find();
            if(!$article)$this->error('找不到文章');
            $article['image'] =  __ROOT__ . '/static/uploads/'.str_replace('\\',"/",$article['image']);
            $this->assign('data',$article);
        }
        if($this->request->isPost()){
            $title = input('title/s');
            if(empty($title)) $this->error('标题不能为空');
            if(mb_strlen($title) > 30) $this->error('标题字数不能超过30个字');
            $sort = input('sort/s');
            $content = input('content/s');
            if(empty($content)) $this->error('内容不能为空');
            $data = array(
                'title' => htmlspecialchars($title),
                'sort' => htmlspecialchars($sort),
                'content' => htmlspecialchars($content),
                'create_name' => 'AI美食相机',
                'status'=>'1'
            );
            $file = request()->file('image');
            if($file){
                $info = $file->move(ROOT_PATH . 'public/static/uploads');
                if ($info) {
                    $data['image'] = $info->getSaveName();
                }
            }
            if($id > 0){
                if($m_fk->where(['id' => $id])->update($data) === false) $this->error('系统错误');
            }else {
                if(!$file){
                    $this->error('图片不能为空');
                }
                $data['create_time'] = TIMESTAMP;
                if (!$m_fk->insert($data)) $this->error('系统错误');
            }
            $this->redirect(url('KnowFoods/index'));
        }
        return $this->fetch();
    }

    /**
     * 删除
     */
    public function del(){
        $id = input('id/d');
        $m_fk = db('foods_knowledge');
        $article = $m_fk->where(['id' => $id,'status' => array('neq',ARTICLE_STATUS_DELETE)])->find();
        if(!$article)$this->error('找不到文章');
        if($m_fk->where(['id' => $id])->update(['status' => ARTICLE_STATUS_DELETE]) === false) $this->error('删除失败');
        $this->redirect(url('KnowFoods/index'));
    }




}